<template>
  <div class="login-page">
    <!-- 星空银河背景 -->
    <div class="login-bg">
      <!-- 深空背景层 -->
      <div class="bg-gradient"></div>
      <!-- 银河层 -->
      <canvas ref="galaxyCanvas" class="bg-galaxy"></canvas>
      <!-- 星星层 -->
      <canvas ref="starsCanvas" class="bg-stars"></canvas>
      <!-- 星云层 -->
      <div class="bg-nebula">
        <div class="nebula nebula-1"></div>
        <div class="nebula nebula-2"></div>
        <div class="nebula nebula-3"></div>
      </div>
      <!-- 贪吃蛇层 -->
      <canvas ref="snakeCanvas" class="bg-snake"></canvas>
    </div>

    <!-- 登录容器 -->
    <div class="login-wrapper">
      <!-- 左侧品牌区域 -->
      <div class="login-brand">
        <h1 class="brand-name">Mes系统管理平台</h1>
        <p class="brand-desc">高效、安全的企业级管理解决方案</p>
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form-card">
        <h2 class="form-title">账户登录</h2>

        <el-form
          ref="loginForm"
          :model="formData"
          :rules="formRules"
          class="form-container"
        >
          <!-- 用户名输入 -->
          <el-form-item prop="userName">
            <el-input
              v-model="formData.userName"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="pwd">
            <el-input
              v-model="formData.pwd"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              clearable
              show-password
            ></el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code">
            <div class="code-group">
              <el-input
                v-model="formData.code"
                placeholder="请输入验证码"
                prefix-icon="Check"
                clearable
                maxlength="4"
                class="code-input"
              ></el-input>

              <!-- 验证码图片 -->
              <div class="code-canvas" @click="refreshCode">
                <canvas ref="codeCanvas" width="120" height="46"></canvas>
              </div>
            </div>
          </el-form-item>

          <!-- 操作区：记住密码 + 忘记密码 -->
          <div class="form-actions">
            <el-checkbox v-model="formData.remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false" @click="handleForgot"
              >忘记密码?</el-link
            >
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              class="login-btn"
              :loading="isLoading"
              @click="handleSubmit"
            >
              登录系统
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 一键跳过登录按钮 -->
        <div class="quick-login-wrapper">
          <el-button
            type="info"
            plain
            class="quick-login-btn"
            :loading="isLoading"
            @click="quickLogin"
          >
            一键跳过登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import https from "@/Http/http";
import axios from "axios";

// 表单引用
const loginForm: any = ref(null);
// 验证码画布引用
const codeCanvas = ref(null);
// 银河画布引用
const galaxyCanvas = ref(null);
// 星星画布引用
const starsCanvas = ref(null);
// 贪吃蛇画布引用
const snakeCanvas = ref(null);
// 验证码正确值
const codeValue = ref("");
// 加载状态
const isLoading = ref(false);
// 动画帧ID
let galaxyAnimationId: number | null = null;
let starsAnimationId: number | null = null;
let snakeAnimationId: number | null = null;

// 表单数据
const formData = reactive({
  userName: "",
  pwd: "",
  code: "",
  remember: false,
});

// 表单验证规则
const formRules = reactive({
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "用户名长度在 2-20 个字符之间",
      trigger: "blur",
    },
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.toLowerCase() !== codeValue.value.toLowerCase()) {
          callback(new Error("验证码不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

// 生成验证码（4位数字+字母混合）
const generateCode = () => {
  const canvas: any = codeCanvas.value;
  const ctx = canvas.getContext("2d");

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制背景
  ctx.fillStyle = "#f3f4f6";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 随机字符集（数字+大小写字母）
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let code = "";

  // 生成4个随机字符
  for (let i = 0; i < 4; i++) {
    const char = chars[Math.floor(Math.random() * chars.length)];
    code += char;

    // 随机样式
    ctx.fillStyle = `rgb(${Math.random() * 80 + 80}, ${
      Math.random() * 80 + 80
    }, ${Math.random() * 80 + 80})`;
    ctx.font = `${Math.random() * 6 + 18}px Arial`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";

    // 字符随机倾斜和位置偏移
    ctx.transform(
      1,
      Math.random() * 0.4 - 0.2, // 水平倾斜
      Math.random() * 0.4 - 0.2, // 垂直倾斜
      1,
      i * 30 + 20, // x坐标
      23 + (Math.random() * 10 - 5) // y坐标（上下浮动）
    );
    ctx.fillText(char, 0, 0);
    ctx.setTransform(1, 0, 0, 1, 0, 0); // 重置变换
  }

  // 保存正确验证码
  codeValue.value = code;

  // 绘制干扰线（2-4条）
  const lineCount = Math.floor(Math.random() * 3) + 2;
  for (let i = 0; i < lineCount; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 150 + 50}, ${
      Math.random() * 150 + 50
    }, ${Math.random() * 150 + 50})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineWidth = Math.random() * 2 + 1;
    ctx.stroke();
  }

  // 绘制干扰点（20-30个）
  const dotCount = Math.floor(Math.random() * 11) + 20;
  for (let i = 0; i < dotCount; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100 + 100}, ${
      Math.random() * 100 + 100
    }, ${Math.random() * 100 + 100})`;
    ctx.beginPath();
    ctx.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      Math.random() * 1.5 + 0.5,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }
};

// 刷新验证码
const refreshCode = () => {
  generateCode();
};

// 产品数据
const productImage = ref(
  "https://ts1.tc.mm.bing.net/th/id/OIP-C.bxA8Xn8wnbcWY2Q47jWnXwHaEt?w=247&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2"
);

// 登录提交
const handleSubmit = async () => {
  try {
    await loginForm.value.validate();
    isLoading.value = true;

    const { data } = await https.Reads.post("/RBAC/Login", formData);
    if (data.code === 1) {
      ElMessage.success("登录成功，正在跳转...");
      localStorage.setItem("userid", data.data.id);

      if (data.data.menus && Array.isArray(data.data.menus)) {
        localStorage.setItem("userMenus", JSON.stringify(data.data.menus));
      } else {
        localStorage.removeItem("userMenus");
      }

      await router.push("/index");
    } else {
      ElMessage.error(data.msg || "登录失败");
      refreshCode();
    }
  } catch (error) {
    console.error("登录异常:", error);
    ElMessage.error("登录失败，请检查输入或稍后再试");
    refreshCode();
  } finally {
    isLoading.value = false;
  }
};

// 忘记密码处理
const handleForgot = () => {
  ElMessage.info("请联系管理员重置密码");
};

// 一键跳过登录（使用默认账号，跳过验证码）
const quickLogin = () => {
  isLoading.value = true;

  // 设置默认账号密码
  formData.userName = "zhangsan";
  formData.pwd = "123456";
  formData.code = ""; // 清空验证码，因为跳过验证

  // 直接调用登录接口，跳过表单验证
  setTimeout(() => {
    console.log("一键登录参数:", {
      userName: formData.userName,
      pwd: formData.pwd,
      code: formData.code,
      remember: formData.remember,
    });
    axios
      .post("http://localhost:5157/api/RBAC/Login", {
        userName: formData.userName,
        pwd: formData.pwd,
        code: formData.code,
        remember: formData.remember,
      })
      .then((res: any) => {
        if (res.data.code == 1) {
          console.log(res);
          ElMessage.success("登录成功，正在跳转....");
          localStorage.setItem("userid", res.data.data.id);
          // 保存用户菜单数据
          if (res.data.data.menus) {
            localStorage.setItem(
              "userMenus",
              JSON.stringify(res.data.data.menus)
            );
          }
          router.push("/index");
          isLoading.value = false;
        } else {
          ElMessage.error(res.data.msg);
          isLoading.value = false;
        }
      })
      .catch((error: any) => {
        console.error("登录失败:", error);
        ElMessage.error("登录失败，请稍后重试");
        isLoading.value = false;
      });
  }, 500); // 减少延迟，实现更快的无感登录
};

// 绘制银河
const drawGalaxy = () => {
  const canvas: any = galaxyCanvas.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  const width = window.innerWidth;
  const height = window.innerHeight;

  canvas.width = width;
  canvas.height = height;

  ctx.clearRect(0, 0, width, height);

  // 绘制银河带（从左上到右下）
  const time = Date.now() * 0.0001;
  const centerX = width / 2;
  const centerY = height / 2;

  // 创建银河渐变
  const gradient = ctx.createLinearGradient(
    centerX - width * 0.4,
    centerY - height * 0.3,
    centerX + width * 0.4,
    centerY + height * 0.3
  );

  gradient.addColorStop(0, "rgba(25, 25, 112, 0)");
  gradient.addColorStop(0.2, "rgba(72, 61, 139, 0.3)");
  gradient.addColorStop(0.4, "rgba(138, 43, 226, 0.5)");
  gradient.addColorStop(0.5, "rgba(255, 20, 147, 0.6)");
  gradient.addColorStop(0.6, "rgba(138, 43, 226, 0.5)");
  gradient.addColorStop(0.8, "rgba(72, 61, 139, 0.3)");
  gradient.addColorStop(1, "rgba(25, 25, 112, 0)");

  ctx.save();
  ctx.translate(centerX, centerY);
  ctx.rotate(Math.sin(time) * 0.05);
  ctx.translate(-centerX, -centerY);

  // 绘制银河主体
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.ellipse(
      centerX,
      centerY,
      width * 0.5 + Math.sin(time + i) * 20,
      height * 0.15 + Math.cos(time + i) * 10,
      Math.sin(time) * 0.1,
      0,
      Math.PI * 2
    );
    ctx.fillStyle = gradient;
    ctx.globalAlpha = 0.3 - i * 0.05;
    ctx.fill();
  }

  ctx.globalAlpha = 1.0;
  ctx.restore();

  // 添加银河中的亮点
  for (let i = 0; i < 30; i++) {
    const angle = (i / 30) * Math.PI * 2 + time;
    const distance = width * 0.3 + Math.sin(i) * 50;
    const x = centerX + Math.cos(angle) * distance;
    const y = centerY + Math.sin(angle) * distance * 0.3;

    const size = Math.random() * 3 + 1;
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 255, 255, ${0.3 + Math.sin(time + i) * 0.2})`;
    ctx.fill();
  }

  galaxyAnimationId = requestAnimationFrame(drawGalaxy);
};

// 星星系统
interface Star {
  x: number;
  y: number;
  radius: number;
  opacity: number;
  twinkleSpeed: number;
  twinklePhase: number;
  color: string;
}

const stars: Star[] = [];

// 初始化星星
const initStars = () => {
  const canvas: any = starsCanvas.value;
  if (!canvas) return;

  const width = window.innerWidth;
  const height = window.innerHeight;

  canvas.width = width;
  canvas.height = height;

  stars.length = 0;

  // 创建大量星星（500-800颗）
  const starCount = 500 + Math.floor(Math.random() * 300);
  for (let i = 0; i < starCount; i++) {
    const size = Math.random();
    let radius: number;
    let color: string;

    // 根据大小分配不同的星星类型
    if (size > 0.7) {
      // 大星星（较亮）
      radius = Math.random() * 2 + 1.5;
      color = "rgba(255, 255, 255, 1)";
    } else if (size > 0.4) {
      // 中等星星
      radius = Math.random() * 1.5 + 0.8;
      color = "rgba(200, 200, 255, 1)";
    } else {
      // 小星星（较暗）
      radius = Math.random() * 1 + 0.3;
      color = "rgba(150, 150, 200, 1)";
    }

    stars.push({
      x: Math.random() * width,
      y: Math.random() * height,
      radius,
      opacity: Math.random() * 0.5 + 0.3,
      twinkleSpeed: Math.random() * 0.02 + 0.01,
      twinklePhase: Math.random() * Math.PI * 2,
      color,
    });
  }
};

// 绘制星星
const drawStars = () => {
  const canvas: any = starsCanvas.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  const width = canvas.width;
  const height = canvas.height;

  // 检查是否需要调整画布大小
  if (width !== window.innerWidth || height !== window.innerHeight) {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    initStars();
    return;
  }

  ctx.clearRect(0, 0, width, height);

  const time = Date.now() * 0.001;

  // 绘制星星
  stars.forEach((star) => {
    // 更新闪烁相位
    star.twinklePhase += star.twinkleSpeed;

    // 计算闪烁透明度
    const twinkle = Math.sin(star.twinklePhase) * 0.3 + 0.7;
    const opacity = star.opacity * twinkle;

    // 绘制星星光晕（大星星才有）
    if (star.radius > 1.5) {
      const glowGradient = ctx.createRadialGradient(
        star.x,
        star.y,
        0,
        star.x,
        star.y,
        star.radius * 3
      );
      glowGradient.addColorStop(
        0,
        star.color.replace("1)", `${opacity * 0.5})`)
      );
      glowGradient.addColorStop(1, star.color.replace("1)", "0)"));

      ctx.beginPath();
      ctx.arc(star.x, star.y, star.radius * 3, 0, Math.PI * 2);
      ctx.fillStyle = glowGradient;
      ctx.fill();
    }

    // 绘制星星本体
    ctx.beginPath();
    ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
    ctx.fillStyle = star.color.replace("1)", `${opacity})`);
    ctx.fill();

    // 大星星添加十字光芒
    if (star.radius > 1.5) {
      ctx.strokeStyle = star.color.replace("1)", `${opacity * 0.5})`);
      ctx.lineWidth = 0.5;
      ctx.beginPath();
      ctx.moveTo(star.x - star.radius * 2, star.y);
      ctx.lineTo(star.x + star.radius * 2, star.y);
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(star.x, star.y - star.radius * 2);
      ctx.lineTo(star.x, star.y + star.radius * 2);
      ctx.stroke();
    }
  });

  starsAnimationId = requestAnimationFrame(drawStars);
};

// 贪吃蛇系统
interface SnakeSegment {
  x: number;
  y: number;
}

interface Food {
  x: number;
  y: number;
  size: number;
  pulse: number;
  color: string; // 食物颜色
  glowColor: string; // 光晕颜色
}

interface Snake {
  segments: SnakeSegment[];
  direction: { x: number; y: number };
  color: string; // 蛇的主色
  headColor: string; // 蛇头颜色
  bodyGradient: string[]; // 蛇身渐变色
  lastMoveTime: number;
}

// 5种蛇的颜色配置
const SNAKE_COLORS = [
  {
    main: "rgba(0, 255, 255, 1)", // 青色
    head: "rgba(0, 255, 255, 1)",
    body: ["rgba(0, 200, 255, 1)", "rgba(0, 150, 200, 1)"],
  },
  {
    main: "rgba(255, 0, 150, 1)", // 粉红色
    head: "rgba(255, 0, 150, 1)",
    body: ["rgba(255, 50, 180, 1)", "rgba(200, 0, 120, 1)"],
  },
  {
    main: "rgba(0, 255, 0, 1)", // 绿色
    head: "rgba(0, 255, 0, 1)",
    body: ["rgba(50, 255, 50, 1)", "rgba(0, 200, 0, 1)"],
  },
  {
    main: "rgba(255, 165, 0, 1)", // 橙色
    head: "rgba(255, 165, 0, 1)",
    body: ["rgba(255, 200, 50, 1)", "rgba(255, 140, 0, 1)"],
  },
  {
    main: "rgba(138, 43, 226, 1)", // 紫色
    head: "rgba(138, 43, 226, 1)",
    body: ["rgba(160, 80, 240, 1)", "rgba(100, 20, 200, 1)"],
  },
];

// 食物颜色配置
const FOOD_COLORS = [
  { color: "rgba(0, 255, 255, 0.9)", glow: "rgba(0, 255, 255, 0.8)" }, // 青色
  { color: "rgba(255, 0, 150, 0.9)", glow: "rgba(255, 0, 150, 0.8)" }, // 粉红色
  { color: "rgba(0, 255, 0, 0.9)", glow: "rgba(0, 255, 0, 0.8)" }, // 绿色
  { color: "rgba(255, 165, 0, 0.9)", glow: "rgba(255, 165, 0, 0.8)" }, // 橙色
  { color: "rgba(138, 43, 226, 0.9)", glow: "rgba(138, 43, 226, 0.8)" }, // 紫色
  { color: "rgba(255, 20, 147, 0.9)", glow: "rgba(255, 20, 147, 0.8)" }, // 深粉色
  { color: "rgba(255, 215, 0, 0.9)", glow: "rgba(255, 215, 0, 0.8)" }, // 金色
  { color: "rgba(64, 224, 208, 0.9)", glow: "rgba(64, 224, 208, 0.8)" }, // 青绿色
];

const snakes: Snake[] = [];
const foods: Food[] = [];
const GRID_SIZE = 20; // 网格大小
let moveInterval = 100; // 移动间隔（毫秒）

// 初始化贪吃蛇（5条蛇）
const initSnake = () => {
  const canvas: any = snakeCanvas.value;
  if (!canvas) return;

  const width = window.innerWidth;
  const height = window.innerHeight;

  canvas.width = width;
  canvas.height = height;

  // 清空蛇和食物
  snakes.length = 0;
  foods.length = 0;

  // 初始化5条蛇，分布在屏幕不同位置
  const startPositions = [
    { x: width * 0.2, y: height * 0.2, dir: { x: 1, y: 0 } }, // 左上，向右
    { x: width * 0.8, y: height * 0.2, dir: { x: -1, y: 0 } }, // 右上，向左
    { x: width * 0.2, y: height * 0.8, dir: { x: 0, y: -1 } }, // 左下，向上
    { x: width * 0.8, y: height * 0.8, dir: { x: -1, y: 0 } }, // 右下，向左
    { x: width * 0.5, y: height * 0.5, dir: { x: 1, y: 0 } }, // 中心，向右
  ];

  startPositions.forEach((pos, index) => {
    const colorConfig = SNAKE_COLORS[index];
    if (!colorConfig) return;

    const segments: SnakeSegment[] = [];
    const startX = Math.floor(pos.x / GRID_SIZE) * GRID_SIZE;
    const startY = Math.floor(pos.y / GRID_SIZE) * GRID_SIZE;

    // 每条蛇初始3段
    for (let i = 0; i < 3; i++) {
      segments.push({
        x: startX - i * pos.dir.x * GRID_SIZE,
        y: startY - i * pos.dir.y * GRID_SIZE,
      });
    }

    snakes.push({
      segments,
      direction: pos.dir,
      color: colorConfig.main,
      headColor: colorConfig.head,
      bodyGradient: colorConfig.body,
      lastMoveTime: Date.now() + index * 20, // 错开移动时间，更自然
    });
  });

  // 生成初始食物（15个，各种颜色）
  for (let i = 0; i < 15; i++) {
    generateFood();
  }
};

// 生成食物（随机颜色）
const generateFood = () => {
  const canvas: any = snakeCanvas.value;
  if (!canvas) return;

  const width = canvas.width;
  const height = canvas.height;

  let foodX = 0;
  let foodY = 0;
  let isValid = false;

  // 确保食物不会生成在蛇身上
  while (!isValid) {
    foodX =
      Math.floor((Math.random() * (width - 100)) / GRID_SIZE) * GRID_SIZE +
      GRID_SIZE / 2;
    foodY =
      Math.floor((Math.random() * (height - 100)) / GRID_SIZE) * GRID_SIZE +
      GRID_SIZE / 2;

    isValid = true;

    // 检查是否与所有蛇重叠
    for (const snake of snakes) {
      for (const segment of snake.segments) {
        if (
          Math.abs(segment.x - foodX) < GRID_SIZE &&
          Math.abs(segment.y - foodY) < GRID_SIZE
        ) {
          isValid = false;
          break;
        }
      }
      if (!isValid) break;
    }

    // 确保食物不会与现有食物重叠
    for (const food of foods) {
      if (
        Math.abs(food.x - foodX) < GRID_SIZE &&
        Math.abs(food.y - foodY) < GRID_SIZE
      ) {
        isValid = false;
        break;
      }
    }
  }

  // 随机选择食物颜色
  const colorConfig =
    FOOD_COLORS[Math.floor(Math.random() * FOOD_COLORS.length)];
  if (!colorConfig) return;

  foods.push({
    x: foodX,
    y: foodY,
    size: GRID_SIZE * 0.6,
    pulse: Math.random() * Math.PI * 2,
    color: colorConfig.color,
    glowColor: colorConfig.glow,
  });
};

// 计算蛇头到食物的方向
const getDirectionToFood = (
  head: SnakeSegment,
  food: Food
): { x: number; y: number } => {
  const dx = food.x - head.x;
  const dy = food.y - head.y;

  // 优先选择距离更短的方向
  if (Math.abs(dx) > Math.abs(dy)) {
    return { x: dx > 0 ? 1 : -1, y: 0 };
  } else {
    return { x: 0, y: dy > 0 ? 1 : -1 };
  }
};

// 移动单条蛇
const moveSingleSnake = (snake: Snake) => {
  if (snake.segments.length === 0) return;

  const head = snake.segments[0];
  if (!head) return;

  // 自动寻路：找到最近的食物
  if (foods.length > 0) {
    let nearestFood: Food | null = null;
    let minDistance = Infinity;

    foods.forEach((food) => {
      if (!food) return;
      const distance = Math.sqrt(
        Math.pow(food.x - head.x, 2) + Math.pow(food.y - head.y, 2)
      );
      if (distance < minDistance) {
        minDistance = distance;
        nearestFood = food;
      }
    });

    // 计算方向（带一点随机性，让蛇更自然）
    if (nearestFood) {
      const targetDirection = getDirectionToFood(head, nearestFood);

      // 70%概率朝食物方向，30%概率保持当前方向或随机
      if (Math.random() > 0.3) {
        // 避免反向（防止蛇撞到自己）
        if (
          !(
            snake.direction.x === -targetDirection.x &&
            snake.direction.y === -targetDirection.y
          )
        ) {
          snake.direction = targetDirection;
        }
      }
    }
  }

  // 计算新头部位置
  const newHead = {
    x: head.x + snake.direction.x * GRID_SIZE,
    y: head.y + snake.direction.y * GRID_SIZE,
  };

  // 边界检测（穿墙）
  const canvas: any = snakeCanvas.value;
  if (canvas) {
    if (newHead.x < 0) newHead.x = canvas.width - GRID_SIZE;
    if (newHead.x >= canvas.width) newHead.x = 0;
    if (newHead.y < 0) newHead.y = canvas.height - GRID_SIZE;
    if (newHead.y >= canvas.height) newHead.y = 0;
  }

  // 检测是否吃到食物
  let ateFood = false;
  for (let i = foods.length - 1; i >= 0; i--) {
    const food = foods[i];
    if (!food) continue;

    const distance = Math.sqrt(
      Math.pow(newHead.x - food.x, 2) + Math.pow(newHead.y - food.y, 2)
    );

    if (distance < GRID_SIZE) {
      // 吃到食物
      snake.segments.unshift(newHead);
      foods.splice(i, 1);
      ateFood = true;
      generateFood(); // 生成新食物
      break;
    }
  }

  if (!ateFood) {
    // 正常移动
    snake.segments.unshift(newHead);
    snake.segments.pop();
  }
};

// 移动所有蛇
const moveSnake = () => {
  const now = Date.now();
  snakes.forEach((snake) => {
    if (now - snake.lastMoveTime > moveInterval) {
      moveSingleSnake(snake);
      snake.lastMoveTime = now;
    }
  });
};

// 绘制贪吃蛇
const drawSnake = () => {
  const canvas: any = snakeCanvas.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  const width = canvas.width;
  const height = canvas.height;

  // 检查是否需要调整画布大小
  if (width !== window.innerWidth || height !== window.innerHeight) {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  // 移动所有蛇
  moveSnake();

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制食物（带脉冲效果，使用各自颜色）
  foods.forEach((food) => {
    food.pulse += 0.1;
    const pulseSize = food.size + Math.sin(food.pulse) * 3;

    // 外层光晕（使用食物的光晕颜色）
    const gradient = ctx.createRadialGradient(
      food.x,
      food.y,
      0,
      food.x,
      food.y,
      pulseSize * 2
    );
    gradient.addColorStop(0, food.glowColor.replace("0.8", "0.6"));
    gradient.addColorStop(0.5, food.glowColor.replace("0.8", "0.3"));
    gradient.addColorStop(1, food.glowColor.replace("0.8", "0"));

    ctx.beginPath();
    ctx.arc(food.x, food.y, pulseSize * 2, 0, Math.PI * 2);
    ctx.fillStyle = gradient;
    ctx.fill();

    // 食物本体（使用食物的颜色）
    ctx.beginPath();
    ctx.arc(food.x, food.y, pulseSize, 0, Math.PI * 2);
    ctx.fillStyle = food.color;
    ctx.fill();

    // 高光
    ctx.beginPath();
    ctx.arc(
      food.x - pulseSize * 0.3,
      food.y - pulseSize * 0.3,
      pulseSize * 0.3,
      0,
      Math.PI * 2
    );
    ctx.fillStyle = "rgba(255, 255, 255, 0.6)";
    ctx.fill();
  });

  // 绘制所有蛇（每条蛇使用不同颜色）
  snakes.forEach((snake) => {
    snake.segments.forEach((segment, index) => {
      const progress = index / snake.segments.length;
      const alpha = 0.6 + progress * 0.4;
      const size = GRID_SIZE * (0.85 + progress * 0.15);

      // 蛇身渐变（使用蛇的配置颜色）
      const gradient = ctx.createRadialGradient(
        segment.x,
        segment.y,
        0,
        segment.x,
        segment.y,
        size
      );

      if (index === 0) {
        // 蛇头：使用蛇头颜色
        const headColor = snake.headColor.replace("1)", `${alpha})`);
        gradient.addColorStop(0, headColor);
        gradient.addColorStop(
          1,
          headColor.replace(`${alpha}`, `${alpha * 0.5}`)
        );
      } else {
        // 蛇身：使用蛇身渐变色
        const bodyColor1 =
          snake.bodyGradient[0]?.replace("1)", `${alpha})`) ||
          snake.color.replace("1)", `${alpha})`);
        const bodyColor2 =
          snake.bodyGradient[1]?.replace("1)", `${alpha * 0.5})`) ||
          snake.color.replace("1)", `${alpha * 0.5})`);
        gradient.addColorStop(0, bodyColor1);
        gradient.addColorStop(1, bodyColor2);
      }

      // 使用圆形绘制蛇身（更流畅）
      ctx.beginPath();
      ctx.arc(segment.x, segment.y, size / 2, 0, Math.PI * 2);
      ctx.fillStyle = gradient;
      ctx.fill();

      // 蛇头眼睛
      if (index === 0) {
        const eyeSize = size * 0.15;
        const eyeOffset = size * 0.25;

        // 根据蛇的方向调整眼睛位置
        const eyeX1 =
          segment.x - eyeOffset * (snake.direction.y === 0 ? 1 : 0.5);
        const eyeY1 =
          segment.y - eyeOffset * (snake.direction.x === 0 ? 1 : 0.5);
        const eyeX2 =
          segment.x + eyeOffset * (snake.direction.y === 0 ? 1 : 0.5);
        const eyeY2 =
          segment.y - eyeOffset * (snake.direction.x === 0 ? 1 : 0.5);

        ctx.beginPath();
        ctx.arc(eyeX1, eyeY1, eyeSize, 0, Math.PI * 2);
        ctx.fillStyle = "rgba(255, 255, 255, 0.9)";
        ctx.fill();

        ctx.beginPath();
        ctx.arc(eyeX2, eyeY2, eyeSize, 0, Math.PI * 2);
        ctx.fillStyle = "rgba(255, 255, 255, 0.9)";
        ctx.fill();
      }
    });
  });

  snakeAnimationId = requestAnimationFrame(drawSnake);
};

// 窗口大小改变时重新初始化
const handleResize = () => {
  if (galaxyCanvas.value) {
    const canvas: any = galaxyCanvas.value;
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }
  if (starsCanvas.value) {
    initStars();
  }
  if (snakeCanvas.value) {
    initSnake();
  }
};

// 页面加载时生成初始验证码和启动动画
onMounted(() => {
  generateCode();
  initStars();
  initSnake();
  drawGalaxy();
  drawStars();
  drawSnake();
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  if (galaxyAnimationId) cancelAnimationFrame(galaxyAnimationId);
  if (starsAnimationId) cancelAnimationFrame(starsAnimationId);
  if (snakeAnimationId) cancelAnimationFrame(snakeAnimationId);
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="scss">
.login-page {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative; // 为背景图提供定位上下文
}

// 动态高科技背景样式
.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; // 置于底层
  overflow: hidden;

  // 深空背景层
  .bg-gradient {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(
      ellipse at center,
      #1a0033 0%,
      #0d0019 25%,
      #000000 50%,
      #0d0019 75%,
      #1a0033 100%
    );
    background-size: 200% 200%;
    animation: gradientShift 20s ease infinite;
  }

  // 银河画布
  .bg-galaxy {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0.8;
  }

  // 星星画布
  .bg-stars {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 1;
  }

  // 星云层
  .bg-nebula {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .nebula {
      position: absolute;
      border-radius: 50%;
      filter: blur(100px);
      opacity: 0.4;
      animation: nebulaFloat 30s ease-in-out infinite;

      &.nebula-1 {
        width: 800px;
        height: 600px;
        background: radial-gradient(
          circle,
          rgba(138, 43, 226, 0.6),
          rgba(72, 61, 139, 0.3),
          transparent
        );
        top: -200px;
        left: -200px;
        animation-delay: 0s;
      }

      &.nebula-2 {
        width: 600px;
        height: 800px;
        background: radial-gradient(
          circle,
          rgba(255, 20, 147, 0.5),
          rgba(138, 43, 226, 0.3),
          transparent
        );
        bottom: -300px;
        right: -200px;
        animation-delay: 10s;
      }

      &.nebula-3 {
        width: 700px;
        height: 500px;
        background: radial-gradient(
          circle,
          rgba(25, 25, 112, 0.4),
          rgba(72, 61, 139, 0.2),
          transparent
        );
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        animation-delay: 20s;
      }
    }
  }

  // 贪吃蛇画布
  .bg-snake {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0.85;
  }
}

// 渐变流动动画
@keyframes gradientShift {
  0% {
    background-position: 0% 0%;
  }
  50% {
    background-position: 100% 100%;
  }
  100% {
    background-position: 0% 0%;
  }
}

// 星云浮动动画
@keyframes nebulaFloat {
  0%,
  100% {
    transform: translate(0, 0) scale(1) rotate(0deg);
    opacity: 0.4;
  }
  25% {
    transform: translate(150px, -100px) scale(1.1) rotate(5deg);
    opacity: 0.5;
  }
  50% {
    transform: translate(-100px, 200px) scale(0.9) rotate(-5deg);
    opacity: 0.3;
  }
  75% {
    transform: translate(-150px, -50px) scale(1.05) rotate(3deg);
    opacity: 0.45;
  }
}

.product-img {
  width: 110px;
  height: 50px;
  border-radius: 4px;
  margin-bottom: -32px;
}

.login-wrapper {
  width: 100%;
  max-width: 900px;
  background: rgba(255, 255, 255, 0.95); // 半透明白色背景
  border-radius: 10px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15); // 增强阴影，提升层次感
  display: flex;
  overflow: hidden;
  backdrop-filter: blur(8px); // 毛玻璃效果，增强质感
}

// 品牌区域样式
.login-brand {
  flex: 1;
  padding: 40px;
  background: linear-gradient(
    135deg,
    rgba(22, 93, 255, 0.9),
    rgba(10, 36, 99, 0.95)
  ); // 半透明渐变
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .brand-name {
    font-size: 28px;
    margin-bottom: 15px;
    font-weight: 600;
  }

  .brand-desc {
    font-size: 16px;
    opacity: 0.9;
    max-width: 300px;
  }
}

// 表单卡片样式
.login-form-card {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;

  .form-title {
    font-size: 22px;
    color: #1d2129;
    margin-bottom: 30px;
    text-align: center;
    font-weight: 500;
  }

  .form-container {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }

  // 验证码区域样式
  .code-group {
    display: flex;
    gap: 10px;
    align-items: center;

    .code-input {
      flex: 1;
    }

    .code-canvas {
      width: 120px;
      height: 46px;
      border-radius: 4px;
      cursor: pointer;
      overflow: hidden;
    }
  }

  .form-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    font-size: 14px;
  }

  .login-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
  }
}

// 一键登录按钮样式
.quick-login-wrapper {
  width: 100%;
  max-width: 300px;
  margin: 10px auto 0;
  text-align: center;

  .quick-login-btn {
    width: 100%;
    height: 36px;
    font-size: 14px;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .login-wrapper {
    flex-direction: column;
  }

  .login-brand {
    padding: 30px;
    text-align: center;
  }

  .brand-desc {
    margin: 0 auto;
  }

  .login-form-card {
    padding: 30px 20px;
  }

  .code-group .code-canvas {
    width: 100px;
  }
}
</style>
